package cn.ainit.test.web;
/***
 * 开发要点：
 *  1.返回json数据 
	    @RequestMapping("/getAllUser")
	    @ResponseBody	//springMVC 内置注解，返回json数据
	  	public List<User> getAllUser(String uid,HttpServletRequest request){
	  		......
	  		List<User> users = new ArrayList<User>();
	  		...
	  		return columns;
	  	}
 	
 	2.返回menu   Map
 	 @ResponseBody	
 	 public Map<String, List<FunctionsObjs>>  getLeftMenus(){
 	 	Map<String, List<Function>> leftMenus = new HashMap<String, List<Menu>>();
		List<FunctionsObjs> functions = ...
		fucntions = 
		leftMenus.put("menus",functions);
		return leftMenus;
 	 }
 	
 	class Function{
 		menuid    
 		icon   
 		menuname  
 		url
 		parent
 	} 
 	
 	class FunctionsObjs{
 		supperFunction
 		Map<"menus",List<Fuction>>
 	}

 */
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/user")
public class UserController {
	
	private UserManager userManager;
	
	@Resource
	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}	
	
	@RequestMapping("/getAllUser")
	@ResponseBody
	public String getAllUser(HttpServletRequest request){
		request.setAttribute("userList", userManager.getAllUser());
		return "";
//		return "/test/index";
	}
	
	@RequestMapping("/getUser")
	public String getUser(String id,HttpServletRequest request){
		request.setAttribute("user", userManager.getUser(id));
		return "/test/editUser";
	}
	
	@RequestMapping("/toAddUser")
	public String toAddUser(){
		return "/test/addUser";
	}
	
	@RequestMapping("/addUser")
	public String addUser(User user,HttpServletRequest request) throws Exception{
		userManager.addUser(user);
		return "redirect:/user/getAllUser";
	}
	
	@RequestMapping("/delUser")
	public void delUser(String id,HttpServletResponse response){
		String result = "{\"result\":\"error\"}";
		if(userManager.delUser(id)){
			result = "{\"result\":\"success\"}";
		}
		response.setContentType("application/json");
		try {
			PrintWriter out = response.getWriter();
			out.write(result);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@RequestMapping("/updateUser")
	public String updateUser(User user,HttpServletRequest request){
		
		if(userManager.updateUser(user)){
			user = userManager.getUser(user.getId());
			request.setAttribute("user", user);
			return "redirect:/user/getAllUser";
		}else{
			return "/test/error";
		}
	}
	
	@RequestMapping("/test")
	@ResponseBody
	public List testTemp(HttpServletRequest request){
		List list = userManager.testTemp();
		return list;
	}
}